<template>
  <div class="app-container">
    <el-form class="queryForms" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery"
          maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" type="info" @click="handleBacks">返回</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="fileList" @selection-change="handleSelectionChange" stripe border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="55" />
      <el-table-column label="文件类型" align="center" prop="categoryName" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="文件名称" align="center" prop="fileName" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="上传时间" align="center" prop="createTime" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="上传人员" align="center" prop="createBy" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handlePreview(scope.row)">预览</el-button>
          <el-button size="mini" type="text" @click="handledownload(scope.row.filePath)">下载</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :close-on-click-modal="false" title="附件" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件类型" prop="categoryId">
          <el-select v-model="form.categoryId" @change="selectName">
            <el-option v-for="item in typeFileLists" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件上传">
          <file-upload @input="inputUrl" v-model="uploadFiles" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog
      title="预览"
      :close-on-click-modal="false"
      :visible.sync="openPreview"
      width="1000px"
      append-to-body
      v-dialogDrag
    >
      <previewExcel
        :previewUrl="previewUrl"
        :previewType="previewType"
      ></previewExcel>
    </el-dialog> -->

    <el-dialog title="在线预览" v-dialogDrag :visible.sync="openPreview" width="900px" append-to-body>
      <div style="display: flex;justify-content: flex-end;margin: 10px;">
        <el-button @click="handledownload(fileUrl)" size="mini" type="primary">下载</el-button>
      </div>
      <PdfViewer v-if="fileTypes === 'pdf' && fileUrl" :fileUrl="fileUrl" @loading="handleLoading"
        @error="handleError" />

      <DocxViewer v-else-if="fileTypes === 'docx' && fileUrl" :fileUrl="fileUrl" @loading="handleLoading"
        @error="handleError" />

      <ExcelViewer v-else-if="fileTypes === 'xlsx' && fileUrl" :fileUrl="fileUrl" @loading="handleLoading"
        @error="handleError" />


      <el-image v-else-if="fileTypes === 'png' || fileTypes === 'jpg' || fileTypes === 'jpeg'"
        style=" width: 100px; height: 100px" :src="fileUrl" :preview-src-list="[fileUrl]">
      </el-image>
    </el-dialog>
  </div>
</template>
<script>
import previewExcel from "@/views/components/previewTemplete/excels.vue";
import {
  listProductFile,
  addProductFile,
  delProductFile,
} from "@/api/file/fileManage";
import { categoryList } from "@/api/select";
import FileUpload from "@/components/FileUpload/index.vue";
import PdfViewer from "@/views/components/PdfViewer.vue";
import DocxViewer from "@/views/components/DocxViewer.vue";
import ExcelViewer from "@/views/components/ExcelViewer.vue";
export default {
  name: "attachmentUpload",
  components: { previewExcel, PdfViewer, DocxViewer, ExcelViewer, FileUpload },
  data() {
    return {
      uploadFiles: [],
      fileUrl: "",
      fileTypes: "docx",
      loadings: false,
      errors: "",
      openPreview: false,
      selectfileName: "",

      previewType: "",
      previewUrl: "",
      uploadList: [],
      rules: {},
      form: {},
      typeFileLists: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 表格数据
      fileList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        categoryId: null,
        categoryName: null,
      },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "文件类型不能为空", trigger: "blur" },
        ],
        files: [{ required: true, message: "附件不能为空", trigger: "blur" }],
      },
      selections: [],
      fileType: "",
    };
  },
  created() {
    this.selectfileName = localStorage.getItem("fileName");
    this.fileType = this.$route.query.fileType;
    this.getList();
  },
  methods: {
    inputUrl(data) {
      this.uploadFiles = data
      this.form.fileName = data[0].name
      this.form.filePath = data[0].url
    },
    handleLoading(loading) {
      this.loadings = loading;
      this.$emit("loading", loading);
    },
    handleError(error) {
      this.errors = error;
      this.$emit("error", error);
    },
    selectName(e) {
      this.form.categoryName = this.typeFileLists.find(
        (item) => item.id == e
      ).name;
    },
    handleBacks() {
      const obj = { path: this.$route.path };
      this.$tab.closePage(obj).then(() => {
        if (this.$route.query.paths) {
          this.$router.push({
            path: this.$route.query.paths,
            query: {
              queryData: this.$route.query.queryParams,
            },
          });
        } else {
          this.$router.go(-1);
        }
      });
    },
    handlePreview(row) {
      this.fileUrl = row.filePath;

      const extension = this.fileUrl.split(".").pop().toLowerCase();
      this.fileTypes = extension;
      this.openPreview = true;
    },
    submitFileForm() {
      this.$refs["form"].validate((valid) => {
        (this.form.projectId = this.$route.query.projectId),
          (this.form.fileType = this.fileType);
        addProductFile(this.form).then((res) => {
          this.open = false;
          this.$modal.msgSuccess("设置成功");
          this.getList();
        });
      });
    },
    getfileoption() {
      categoryList({
        categoryIds: this.selectfileName.split(","),
      }).then((res) => {
        this.typeFileLists = res.rows;
        this.open = true;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.$route.query.projectId;
      this.queryParams.categoryIds = this.selectfileName.split(",");
      this.queryParams.fileType = this.fileType;
      listProductFile(this.queryParams).then((response) => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        categoryName: null,
        fileName: null,
        filePath: null,
      };
      this.uploadFiles = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selections = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getfileoption();
    },
    // 下载
    handledownload(filePath) {
      window.open(filePath);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除附件？")
        .then(function () {
          return delProductFile(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
